package com.wanglianyun.config.filter;

import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.annotation.Annotation;

/**
 * Description: 增加日志的链路跟踪traceId
 * Copyright: Copyright (c) 2024
 * Create Time: 2024-11-14 09:58
 *
 * @author wanglianyun
 */
@Configuration
public class LogFilter extends OncePerRequestFilter implements Ordered {

    private final static String MDC_TRACE_ID = "traceId";

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String traceId = getMdcTraceId();
        MDC.put(MDC_TRACE_ID, traceId);
        filterChain.doFilter(request, response);
        MDC.clear();
    }

    private String getMdcTraceId() {
        long currentTime = System.nanoTime();
        return String.join("_", MDC_TRACE_ID, String.valueOf(currentTime));
    }
}
